<?php
/**
 * 用户中心
 */
namespace app\api\model;
use app\common\model\Member as MemberModel;
use app\api\model\MemberLevel as MemberLevelModel;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use app\common\common;

class Member extends MemberModel
{
    /**
     * 添加账号
     * @param $address  用户地址
     * @param $pid  上级用户
     * @param $position 矩阵位置
     * @param $private_key 助记词
     * @param $team_id 团队
     * @param $password 密码
     * @param $login_cryptosalt 密码盐
     * @return int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function add($address,$pid,$position,$private_key,$team_id,$password,$login_cryptosalt)
    {
        $level = MemberLevelModel::getDefault();

        $data = [
            'username'   =>  $address,
            'pid'  =>  $pid,
            'position'  =>  $position,  //矩阵位置
            'level_id'   => $level['id'],
            'private_key'    =>  $private_key,   //私钥
            'invitation' =>  self::createInvitecode(),
            'team_id'    =>  $team_id,
            'password'   =>  $password,
            'login_cryptosalt'   =>  $login_cryptosalt,
            'create_time'    =>  time(),
        ];
        $id = self::insertGetId($data);
        return $id;
    }

    /**
     * 录入助记词、私钥和密码
     * @param $mid  用户ID
     * @param $mnemonic 助记词
     * @param $password 密码
     * @param $membername 用户名
     * @return bool
     */
    public static function up_mnemonic_password($mid,$mnemonic,$password,$membername){
        self::where('id',$mid)->update(['mnemonic'=>$mnemonic,'password'=>md5($password),'type'=>1,'membername'=>$membername]);
        return true;
    }

    /**
     * 随机生成6位字符串和数字
     * @return string
     */
    private static function createInvitecode() {
        // 生成字母和数字组成的6位字符串

        $str = range('A', 'Z');
        // 去除大写的O，以防止与0混淆
        unset($str[array_search('O', $str)]);
        $arr = array_merge(range(0, 9), $str);
        shuffle($arr);
        $invitecode = '';
        $arr_len = count($arr);
        for ($i = 0; $i < 6; $i++) {
            $rand = mt_rand(0, $arr_len - 1);
            $invitecode .= $arr[$rand];
        }

        return $invitecode;
    }

    /**
     * 根据排位查询用户 是否存在
     * @param $num  排位序号
     */
    public static function position($num){
        $data = self::where('position',$num)->field('id,username,power,position,level_id,status')->find();
        if(empty($data)){
            return [
                'position'   =>  $num,
                'username'   =>  '',
                'level_id'   =>  '',
                'status'   =>  '',
                'id'   =>  '',
                'power' =>  '',
            ];
        }else{
            return $data->toArray();
        }
    }

    /**
     * 根据用户邀请码查询该
     * @param $invitation 用户地址
     * @return Member|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function invitation($invitation){
        return self::where('invitation',$invitation)->field('id,pid,team_id,direct,invitation,level_id,status')->find();
    }

    /**
     * 签到
     * @param $mid  用户ID
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function up_sign($mid){
        $info = self::getDetails($mid);
        $time = strtotime(date("Y-m-d",time()));
        if($info['sign_time'] > $time){ //判断我最新签到时间是否大于今天0晨
            return false;   //已签到
        }else{
            //查询奖励
            $sign_reward = BaseConfig::config_data('sign_reward');
            //更新签到时间
            self::where('id',$mid)->update(['sign_time'=>time()]);
            //发放签到奖励
            UserMoneyLogModel::change($mid,'lcc',$sign_reward,'Sign in reward','','每日签到奖励');
            return true;
        }
    }


    /**
     * 修改密码
     * @param $address  用户地址
     * @param $password 修改密码
     * @param $name 修改用户名称
     * @return bool
     */
    public static function up_password($id,$password = '',$name = ''){
        $data = [];
        if(!empty($password)) $data['password'] = $password;
        if(!empty($name)) $data['membername'] = $name;
        self::where('id',$id)->update($data);
        return true;
    }

    /**
     * 验证用户密码
     * @param $mid  用户ID
     * @param $password 密码
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function verify_password($mid,$password){
        $member = self::where('id',$mid)->find();
        if(md5($password.$member['login_cryptosalt']) != $member['password']) return false;
        return true;
    }

    /**
     * 通过私钥获取用户信息
     * @param $private_key
     * @return Member|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function key_details($private_key){
        return self::where('private_key',$private_key)->find();
    }

    /**
     * 直推+1
     * @param $mid 用户ID
     */
    public static function directAdd($mid,$direct){
        self::where('id',$mid)->update(['direct'=>$direct]);
    }

    /**
     * 查询我的上级矩阵用户：等级大于或等于我的
     * @param $position 当前位置
     * @param $lid  用户等级ID
     * @param array $levelArr   等级数组
     * @param array $pidArr   查询到的用户数组
     * @param int $ceng 层数或人数
     * @param int $type 1：层数 2：人数
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function matrixLevelSuperior($position,$lid,$levelArr=[],$pidArr=[],$ceng = 10,$type=1){
        if($ceng == 0) return $pidArr;
        if(empty($levelArr)) $levelArr = MemberLevelModel::column('id,level','id');
        if($ceng > 0){
            //已经是最顶层用户
            if($position == 1) return $pidArr;
            //根据矩阵位置查询上级用户
            $member = common::superior_matrix($position);
            //没有该上级用户
            if(empty($member)) return $pidArr;

            if($levelArr[$member['level_id']]['level'] >= $levelArr[$lid]['level']){
                $pidArr[] =  [
                    'id'    =>$member['id'],
                    'power' =>  $member['power']
                ];
            }
            //递归查询
            $pidArr = self::matrixLevelSuperior($member['position'],$lid,$levelArr,$pidArr,$ceng,$type);
        }
        return $pidArr;
    }

}